package redis_api

import (
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
	redis_core "go_server/game_server/database/redis"
	"go_server/zinx/zlog"
)

const (
	ROLE_MAP_KEY = "role_map_info"
)

func GetRoleMapInfoFromRedis(roleId int64, mapId int32, row int32, column int32) ([]redis.Cmder, bool) {
	redis_client := redis_core.GetGameRedisClient()
	key := fmt.Sprintf("%d-%d-%s", roleId, mapId, ROLE_MAP_KEY)
	ctx := context.Background()
	ret, err := redis_client.Exists(ctx, key).Result()
	if err != nil || ret == 0 {
		return nil, false
	}
	cmds, err := redis_client.Pipelined(context.Background(), func(pipe redis.Pipeliner) error {
		for i := int32(0); i < row; i++ {
			for j := int32(0); j < column; j++ {
				pipe.GetBit(ctx, key, int64(j*100+i))
			}
		}
		return nil
	})

	if err != nil {
		return nil, false
	}
	return cmds, true
}

func SetRoleMapInfo(roleId int64, mapId int32, maps [][]byte) {
	key := fmt.Sprintf("%d-%d-%s", roleId, mapId, ROLE_MAP_KEY)
	redis_client := redis_core.GetGameRedisClient()
	ctx := context.Background()
	_, err := redis_client.Pipelined(ctx, func(pipe redis.Pipeliner) error {
		for row, arr := range maps {
			for column, value := range arr {
				pipe.SetBit(ctx, key, int64(column*100+row), int(value))
			}
		}
		return nil
	})
	if err != nil {
		zlog.Errorf("SetRoleMapInfo err!!! roleid: %d, mapId: %d, err: %v", roleId, mapId, err)
	}
}

